package com.ewancle.proxydownload.controller;

/*import com.example.service.ImageDownloadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;*/
import com.ewancle.proxydownload.service.ImageDownloadService;
import jakarta.validation.constraints.NotBlank;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

//import javax.validation.constraints.NotBlank;
import java.time.Duration;

// 5. REST控制器 - ImageController.java
@RestController
@RequestMapping("/api/v1/images")
@Validated
//@Tag(name = "图片服务", description = "高性能图片下载和处理API")
public class ImageController {

    private final ImageDownloadService imageDownloadService;
    private final DefaultDataBufferFactory bufferFactory = new DefaultDataBufferFactory();

    public ImageController(ImageDownloadService imageDownloadService) {
        this.imageDownloadService = imageDownloadService;
    }

    @GetMapping("/download")
/*    @Operation(summary = "下载图片", description = "从Google图库下载图片并支持压缩")
    @ApiResponse(responseCode = "200", description = "下载成功")
    @ApiResponse(responseCode = "400", description = "请求参数错误")
    @ApiResponse(responseCode = "500", description = "服务器内部错误")*/
    public Mono<ResponseEntity<byte[]>> downloadImage(
            //@Parameter(description = "图片URL", required = true)
            @RequestParam @NotBlank String url,
            //@Parameter(description = "是否启用压缩", example = "true")
            @RequestParam(defaultValue = "true") boolean compress) {

        return imageDownloadService.downloadImage(url, compress)
                .map(imageData -> ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE)
                        .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(imageData.length))
                        .header(HttpHeaders.CACHE_CONTROL, "max-age=3600, public")
                        .header("X-Content-Source", "google-images")
                        .body(imageData))
                .onErrorReturn(ResponseEntity.badRequest().build());
    }

    @GetMapping("/stream")
    //@Operation(summary = "流式下载图片", description = "流式下载图片，支持大文件和低内存占用")
    public Mono<Void> streamImage(
            //@Parameter(description = "图片URL", required = true)
            @RequestParam @NotBlank String url,
            //@Parameter(description = "是否启用压缩", example = "true")
            @RequestParam(defaultValue = "true") boolean compress,
            ServerHttpResponse response) {

        // 设置响应头
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
        response.getHeaders().add(HttpHeaders.CACHE_CONTROL, "max-age=3600, public");
        response.getHeaders().add("X-Content-Source", "google-images");
        response.getHeaders().add("Transfer-Encoding", "chunked");

        Flux<DefaultDataBuffer> dataBufferFlux = imageDownloadService.downloadImageStream(url, compress)
                .map(bytes -> {
                    DefaultDataBuffer buffer = bufferFactory.allocateBuffer(bytes.length);
                    buffer.write(bytes);
                    return buffer;
                })
                .onErrorResume(error -> {
                    response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
                    return Flux.empty();
                });

        return response.writeWith(dataBufferFlux);
    }

    @GetMapping("/health")
    //@Operation(summary = "健康检查", description = "检查服务健康状态")
    public Mono<ResponseEntity<String>> health() {
        return Mono.just(ResponseEntity.ok()
                .contentType(MediaType.TEXT_PLAIN)
                .body("Image service is healthy"));
    }
}
